/**
 * Created by liuzengrong on 2019/8/18.
 */
import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import { TableListData } from './data.d';
import { commonRequest } from './service';

export interface StateType {
  data: TableListData;
}

export type Effect = (
  action: AnyAction,
  // eslint-disable-next-line max-len
  effects: EffectsCommandMap & { select: <T>(func: (state: StateType) => T) => T },
) => void;

export interface ModelType {
  namespace: string;
  state: StateType;
  effects: {
    selct: Effect;
    add: Effect;
    delete: Effect;
    update: Effect;
    batchDelete: Effect;
  };
  reducers: {
    save: Reducer<StateType>;
  };
}

const Model: ModelType = {
  namespace: 'standardModule',

  state: {
    data: {
      list: [],
      pagination: {},
    },
  },

  effects: {
    // @ts-ignore
    *select({ payload, url }, { call, put }) {
      const response = yield call(commonRequest, url, payload, { method: 'GET' });
      if (response.code === '0') {
        yield put({
          type: 'save',
          payload: response.data,
        });
      }
    },
    *add({ payload, url, callback }, { call, put }) {
      const response = yield call(commonRequest, url, payload, { method: 'POST' });
      if (response.code === '0') {
        if (callback) callback();
      }
    },
    *update({ payload, url, callback }, { call, put }) {
      const response = yield call(commonRequest, url, payload, { method: 'POST' });
      if (response.code === '0') {
        if (callback) callback();
      }
    },
    *delete({ payload, url, callback }, { call, put }) {
      
      debugger;

      let paramsArray: string[] = [];
      //拼接参数
      Object.keys(payload).forEach(key => { if (payload[key]) paramsArray.push(key + '=' + payload[key]) });
      if (url.search(/\?/) === -1) {
        url += '?' + paramsArray.join('&');
      } else {
        url += '&' + paramsArray.join('&');
      }
      
      const response = yield call(commonRequest, url, payload, { method: 'DELETE' });
      if (response.code === '0') {
        if (callback) callback();
      }
    },
    *batchDelete({ payload, url, callback }, { call, put }) {
      const response = yield call(commonRequest, url, payload, { method: 'POST' });
      if (response.code === '0') {
        if (callback) callback();
      }
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        data: action.payload,
      };
    },
  },
};

export default Model;
